const parse = (str) => {
  let val
  try {
    val = JSON.parse(str)
  } catch (error) {
    val = null
  }
  return val
}
const stringify = (obj) => {
  let val
  try {
    val = JSON.stringify(obj)
  } catch (error) {
    val = null
  }
  return val
}

export default function useLocalStorage () {
  const setItem = (key, value) => {
    value = stringify(value)
    window.localStorage.setItem(key, value)
  }
  const getItem = (key) => {
    const value = window.localStorage.getItem(key)
    return value ? parse(value) : value
  }
  return {
    setItem,
    getItem
  }
}
